using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ordering
{
    public enum PropertyErrorType { Required, Integrity }

    public abstract class KpmgObject
    {
        public bool IsValid { get; set; }

        public virtual IDictionary<string, string> ToDictionary()
        {
            IDictionary<string, string> dicRet = new Dictionary<string, string>();

            dicRet.Add("IsValid", this.IsValid ? "Y" : "N");

            return dicRet;
        }

        public virtual IDictionary<string, PropertyErrorType> CheckData(bool isBeforeSave)
        {
            return new Dictionary<string, PropertyErrorType>();
        }

        public virtual IDictionary<string, string> FindDifference(KpmgObject objOld)
        {
            if (objOld == null)
                throw new Exception("Invalid parameter");

            IDictionary<string, string> dicNew = this.ToDictionary();
            IDictionary<string, string> dicOld = objOld.ToDictionary();

            IDictionary<string, string> dicRet = new Dictionary<string, string>();
            foreach (KeyValuePair<string, string> kv in dicOld)
            {
                string strOld = kv.Value;
                string strNew = dicNew.ContainsKey(kv.Key) ? dicNew[kv.Key] : "";
                if (strOld != strNew)
                    dicRet.Add(kv.Key, strOld + "->" + strNew);
            }

            return dicRet;
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            foreach (KeyValuePair<string, string> kv in this.ToDictionary())
            {
                string strValue = kv.Value.IndexOf(",") >= 0 ? "[" + kv.Value + "]" : kv.Value;
                sb.Append("," + kv.Key + ":" + strValue);
            }

            if (sb.Length > 0)  //Remove the first ","
                sb.Remove(0, 1);

            return sb.ToString();
        }

        public KpmgObject()
        {
            this.IsValid = true;
        }

        #region protected utility
        protected void CheckPropertyForRequired(ref IDictionary<string, PropertyErrorType> dicRet,
            string propName, string propValue)
        {
            if (String.IsNullOrEmpty(propValue))
                dicRet.Add(propName, PropertyErrorType.Required);
        }

        protected void CheckPropertyForRequired(ref IDictionary<string, PropertyErrorType> dicRet,
            string propName, DateTime propValue)
        {
            if (propValue == DateTime.MinValue)
                dicRet.Add(propName, PropertyErrorType.Required);
        }
        #endregion
    }
}
